package threadCommunication;

/**
 * @Author: WanqingLiu
 * @Date: 2023/02/04/10:59
 * 管程法解决生产者消费者问题
 */
public class TestPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        Productor productor = new Productor(synContainer);
        Consumer consumer = new Consumer(synContainer);
        productor.start();
        consumer.start();
    }
}

// 生产者
class Productor extends Thread{
    SynContainer synContainer;
    public Productor(SynContainer synContainer){
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i=0; i<100; i++){
            System.out.println("生产了" + i + "号位置的只因");
            synContainer.push(new Chicken(i));
        }
    }
}

// 消费者
class Consumer extends Thread{
    SynContainer synContainer;
    public Consumer(SynContainer synContainer){
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i=0; i<100; i++){
            System.out.println("消费了" + i + "号 id 的只因");
            synContainer.pop();
        }
    }
}

// 产品
class Chicken{
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}

// 缓冲区
class SynContainer {
    // 容器大小
    Chicken[] chickens = new Chicken[10];
    // 容器计数器
    int cnt = 0;

    // 生产者生产
    public synchronized  void push(Chicken chicken){
        if(cnt == chickens.length){
            // 通知消费者消费，等待生产\
            try {
                this.wait();
            } catch (InterruptedException e){
                e.printStackTrace();
            }
        }

        // 未满，生产
        chickens[cnt] = chicken;
        cnt++;
        // 生产完，通知消费者消费
        this.notifyAll();
    }

    // 消费者消费
    public synchronized  Chicken pop(){
        // 判断能否消费
        if(cnt == 0){
            // 等待生产者生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        // 消费
        cnt--;
        Chicken chicken = chickens[cnt];

        // 消费完，通知生产者生产
        this.notifyAll();

        return chicken;
    }
}
